package com.ruoyi.srmcontract.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.ruoyi.srmcontract.domain.JacContractPrice;
import com.ruoyi.srmcontract.domain.JacContractPriceList;
import com.ruoyi.srmcontract.mapper.JacContractItemMapper;


import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class JacContractPriceMain {
	@Autowired
	private JacContractItemMapper jacContractItemMapper;
	
	
	  /**
     * 异步执行价格走势更新（异步执行方法和调用它的方法不能放在同一个class里，否则无法不起作用）
     * class A 引用 B B 又引用A的方法  启动会报错  in its raw version as part of a circular reference  （循环引用，死循环）
     * @Async 此处不能用异步执行，使用异步，或造成update、insert锁争用，报Lock wait timeout exceeded
     * @param newperice
     */
    @Synchronized
    @Transactional(rollbackFor = Exception.class)
    public void priceCronMain(JacContractPrice newperice)
    {   
    	//根据数据月份获取英文简写月份，生成各月份需要更新的字段
    	String month = monthTranfer(newperice.getContractmonth());
    	newperice.setMonthvalidold(month + "valid");
    	newperice.setMonthpriceold(month);
    	newperice.setContractcodeold(month + "contractcode");
    	//获取某月某物料趋势表中最新的生效时间
    	Date validdate = jacContractItemMapper.selectMonthValid(newperice);
    	//生效时间为空值直接更新
    	if (validdate == null)
    	{
    		jacContractItemMapper.updateContractPrice(newperice);
    		return;
    	}
    	//当获取到新增物料的生效时间小于等于价格走势表时间时 return
    	if (newperice.getValiddate().compareTo(validdate) <= 0)
    	{
    		return;
    	}
    	else
    	{
    	jacContractItemMapper.updateContractPrice(newperice);
    	}
    	
    }
    
    public void fillPrice(JacContractPrice newperice)
    {
    	String monthvalidold = getMonthString(newperice);
    	newperice.setMonthvalidold(monthvalidold);
    	if (!"-1".equals(monthvalidold))
    	{
    	jacContractItemMapper.updateContractPriceAll(newperice);
    	}
    }
    
    @SuppressWarnings("null")
	public String getMonthString(JacContractPrice newperice)
    {   
    	String result = "-1";
    	StringBuffer monthall = new StringBuffer();
    	String start = monthTranfer(newperice.getContractmonth());
		String startmv = start.concat("valid");
		String startmc = start.concat("contractcode");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
		String valid = sdf2.format(((newperice.getValiddate())));
    	int startmonth = (int) Integer.valueOf(valid.substring(4, 6));
    	int endmonth = (int) Integer.valueOf(newperice.getContractend().substring(4, 6));
    	if (startmonth != endmonth)
    	{
    	for (int i = startmonth + 1;i <= endmonth;i++)
    	{   
    		String m = monthTranfer(i);
    		String mv = m.concat("valid");
    		String mc = m.concat("contractcode");
    		String s = m + "=" + start + ", " + mv + "=" + startmv + ", " + mc + "=" + startmc ;
    		monthall.append(s + ",");
    	}
    	if (monthall.length() > 0)
    	{
    	String month = monthall.deleteCharAt(monthall.length() - 1).toString();
    	log.info("拼接sql : " + month);
    	return  month;
    	}
    	else {
    		return  result;
    	}
    }
    	return  result;
    }
    
    /**
     * 获取并写入本年度的未税价格（物料的最新价格）
     * @param jacContractPrice
     */
    public void fillUntaxPrice(JacContractPrice jacContractPrice)
    {
    	JacContractPriceList jacContractPriceList =jacContractItemMapper.selectContractPrice(jacContractPrice);
    	if (jacContractPriceList == null)
    	{
    		priceCronMain(jacContractPrice);
    		log.error("价格趋势表总无此数据，重新执行价格趋势表插入方法",jacContractPrice);
    		jacContractPriceList =jacContractItemMapper.selectContractPrice(jacContractPrice);
    		if (jacContractPriceList == null)
    		{
    			System.out.println("价格趋势表重新执行价格趋势表插入方法，仍未获取数据，跳过异常数据！"+ jacContractPrice);
    			return;
    		}
    	}
    	String untaxPrice = getItemNewPrice(jacContractPriceList);
    	if ("-1".equals(untaxPrice))
    	{
    		log.error("获取未税价格，未找到最新价格",jacContractPrice);
    	}
    	else {
    		updateUntaxPrice(untaxPrice,jacContractPriceList.getId());
		}
    }
    
    /**
     * 获取并写入上一年的未税价格
     * @param jacContractPrice
     */
    public void fillLastPrice(JacContractPrice jacContractPrice)
    {   
    	//本年度
    	String year = jacContractPrice.getContractyear();
    	//上一年度
    	String lastyear = String.valueOf((Long.valueOf(year) -1));
    	jacContractPrice.setContractyear(lastyear);
    	String lastYearPrice = selectLastYearPrice(jacContractPrice);
    	if (lastYearPrice == null || "".equals(lastYearPrice) || "0".equals(lastYearPrice))
    	{
    		log.info("未获取到上年未税价格",jacContractPrice);
    	}
    	else {
    		jacContractPrice.setLastyearprice(lastYearPrice);
    		jacContractPrice.setContractyear(year);
    		updateLastYearPrice(jacContractPrice);
		}
    }
    
    
    /**
     * 查询上年未税价格 		
     * @param jacContractPriceList
     * @return
     */
    public String  selectLastYearPrice(JacContractPrice jacContractPrice)
    {
    	return jacContractItemMapper.selectLastYearPrice(jacContractPrice);
    }
    
    /**
     * 更新价格走势表上年未税价格
     * @param jacContractPriceList
     * @return
     */
    public int updateLastYearPrice(JacContractPrice jacContractPrice)
    {
    	return jacContractItemMapper.updateLastYearPrice(jacContractPrice);
    }
    
    
    /**
     * 更新价格走势表本年未税价格
     * @param jacContractPriceList
     * @return
     */
    public int updateUntaxPrice(String untaxprice, String id)
    {
    	return jacContractItemMapper.updateUntaxPrice(untaxprice,id);
    }
    
    
    /**
     * 获取价格趋势表中的最新月份价格(从12月份判断是否为空值，第一个不为空的价格则为最新价格)
     * @param month
     * @return
     */
    public String getItemNewPrice(JacContractPriceList jacContractPriceList)
    {   
    	System.out.println("开始获取最新月份价格" + jacContractPriceList);
    	if (jacContractPriceList.getDece() != null && !"".equals(jacContractPriceList.getDece()))
    	{
    		return jacContractPriceList.getDece();
    	}
    	
    	if (jacContractPriceList.getNov() != null && !"".equals(jacContractPriceList.getNov()))
    	{
    		return jacContractPriceList.getNov();
    	}
    	
    	if (jacContractPriceList.getOct() != null && !"".equals(jacContractPriceList.getOct()))
    	{
    		return jacContractPriceList.getOct();
    	}
    	
    	if (jacContractPriceList.getSept() != null && !"".equals(jacContractPriceList.getSept()))
    	{
    		return jacContractPriceList.getSept();
    	}
    	
    	if (jacContractPriceList.getAug() != null && !"".equals(jacContractPriceList.getAug()))
    	{
    		return jacContractPriceList.getAug();
    	}
    	
    	if (jacContractPriceList.getJul() != null && !"".equals(jacContractPriceList.getJul()))
    	{
    		return jacContractPriceList.getJul();
    	}
    	
    	if (jacContractPriceList.getJun() != null && !"".equals(jacContractPriceList.getJun()))
    	{
    		return jacContractPriceList.getJun();
    	}
    	
    	if (jacContractPriceList.getMay() != null && !"".equals(jacContractPriceList.getMay()))
    	{
    		return jacContractPriceList.getMay();
    	}
    	
    	if (jacContractPriceList.getApr() != null && !"".equals(jacContractPriceList.getApr()))
    	{
    		return jacContractPriceList.getApr();
    	}
    	
    	if (jacContractPriceList.getMar() != null && !"".equals(jacContractPriceList.getMar()))
    	{
    		return jacContractPriceList.getMar();
    	}
    	
    	if (jacContractPriceList.getFeb() != null && !"".equals(jacContractPriceList.getFeb()))
    	{
    		return jacContractPriceList.getFeb();
    	}
    	
    	if (jacContractPriceList.getJan() != null && !"".equals(jacContractPriceList.getJan()))
    	{
    		return jacContractPriceList.getJan();
    	}
    	
    	else {
			return "-1";
		}
    	
    }
    
    
    /**
     * 将数字（String）月份转换为英文月份
     * @param month
     * @return
     */
    public String monthTranfer(String month)
    {
    	 switch(month)
    	 {
    	 case "01":
    		 return "jan";
    	 case "02":
    		 return "feb";
    	 case "03":
    		 return "mar";
    	 case "04":
    		 return "apr";
    	 case "05":
    		 return "may";
    	 case "06":
    		 return "jun";
    	 case "07":
    		 return "jul";
    	 case "08":
    		 return "aug";
    	 case "09":
    		 return "sept";
    	 case "10":
    		 return "oct";
    	 case "11":
    		 return "nov";
    	 case "12":
    		 return "dece";
    		 default :
    			 return "";
    	 }
    }
    
    /*
     * 将int月份转换为英文
     */
    public String monthTranfer(int month)
    {
    	 switch(month)
    	 {
    	 case 1:
    		 return "jan";
    	 case 2:
    		 return "feb";
    	 case 3:
    		 return "mar";
    	 case 4:
    		 return "apr";
    	 case 5:
    		 return "may";
    	 case 6:
    		 return "jun";
    	 case 7:
    		 return "jul";
    	 case 8:
    		 return "aug";
    	 case 9:
    		 return "sept";
    	 case 10:
    		 return "oct";
    	 case 11:
    		 return "nov";
    	 case 12:
    		 return "dece";
    		 default :
    			 return "";
    	 }
    }
	
}
